<template>
  <div>
    <Menu />
    <layout>
      <template v-slot:main>
        <el-row>
          <el-col>
            <div>
              <el-tabs :tab-position="tabPosition" class="f_tab" @tab-click="handleClick" v-model="activeName">
                <!-- 个人资料 -->
                <el-tab-pane name="first">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <User />
                      </el-icon>
                      <span>个人信息</span>
                    </span>
                  </template>
                  <div class="user_info_container">
                    <el-card shadow="never">
                      <div class="top_user_info">
                        <div class="user_info_left">
                          <el-avatar :size="100" :src="proxy.$baseImgUrl + userInfoData.data.avatar" />
                        </div>
                        <div class="user_info_right">
                          <div class="user_info_name">{{ userInfoData.data.nickName }}</div>
                          <div class="user_info_desc text_muted">
                            <template v-if="!userInfoData.data.remark">
                              这个人很懒，什么都没留下
                            </template>
                            <template v-else>
                              {{ userInfoData.data.remark }}
                            </template>
                          </div>
                        </div>
                      </div>
                    </el-card>

                    <div style="margin-top:20px">
                      <el-card class="message_container_card" shadow="never">
                        <template #header>
                          <div class="card-header">
                            <span>信息</span>
                            <el-button class="button" :icon="Edit" type="primary" link
                              @click="handleClickEditUserInfo">编辑</el-button>
                          </div>
                        </template>
                        <div class="bottom_user_message">
                          <el-descriptions :column="1" size="large">
                            <el-descriptions-item label="性别">
                              <template v-if="userInfoData.data.sex == 0">
                                男
                              </template>
                              <template v-else>
                                女
                              </template>
                            </el-descriptions-item>
                            <el-descriptions-item label="手机">{{ userInfoData.data.phonenumber }}</el-descriptions-item>
                            <el-descriptions-item label="邮箱">{{ userInfoData.data.email }}</el-descriptions-item>
                            <el-descriptions-item label="获赞数">{{ userInfoData.data.likeNum }}</el-descriptions-item>
                            <el-descriptions-item label="发布数">{{ userInfoData.data.noteNum }}</el-descriptions-item>
                            <el-descriptions-item label="兴趣">
                              <template v-if="userInfoData.data.interestValue">
                                <el-tag size="large" style="margin:8px;margin-top: 0;margin-left: 0;"
                                  v-for="item in userInfoData.data.interestValue.split(',')" :key="item.id">{{ item
                                  }}</el-tag>
                              </template>
                            </el-descriptions-item>
                          </el-descriptions>
                        </div>
                      </el-card>
                    </div>
                  </div>
                </el-tab-pane>
                <!-- 我的博客 -->
                <el-tab-pane name="second">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <Document />
                      </el-icon>
                      <span>我的博客</span>
                    </span>
                  </template>
                  <div class="list_container height_light_bgcolor" v-loading="myArticleLoading"
                    element-loading-text="正在玩命加载中...">
                    <Article v-for="item in myArticleList.data.value"
                      @liked="handleClickArticleLiked($event, item.name)" :key="item.id" :id="item.id"
                      :coverPicture="item.coverPicture" :title="item.title" :description="item.description"
                      :groups="item.groups" :likeNum="item.likeNum" :nickName="item.user.nickName"
                      :commentCount="item.commentCount" :pageViewNum="item.pageViewNum" :createTime="item.createTime"
                      :isLike="item.isLike" :directionId="item.directionId"></Article>
                    <el-empty description="暂无数据~" v-if="!myArticleLoading && myArticleList.total.value <= 0" />
                    <div class="pagination_container">
                      <el-pagination v-model:current-page="myArticleSearchParams.pageNum"
                        v-model:page-size="myArticleSearchParams.pageSize" background
                        layout="total, prev, pager, next, jumper" :total="myArticleList.total.value"
                        v-if="myArticleList.total.value > 0" @current-change="handleCurrentChange($event, 1)" />
                    </div>
                  </div>
                </el-tab-pane>
                <!-- 我的资源 -->
                <el-tab-pane name="third">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <Files />
                      </el-icon>
                      <span>我的资源</span>
                    </span>
                  </template>
                  <div class="list_container height_light_bgcolor">
                    <File v-for="item in myResourceList.data.value" :key="item.id" :title="item.title"
                      :format="item.format" :description="item.description" :id="item.id"
                      :createTime="item.createTime" />
                    <el-empty description="暂无数据~" v-if="!myResourceLoading && myResourceList.total.value <= 0" />
                    <div class="pagination_container">
                      <el-pagination v-model:current-page="myResourceSearchParams.pageNum"
                        v-model:page-size="myResourceSearchParams.pageSize" background
                        layout="total, prev, pager, next, jumper" :total="myResourceList.total.value"
                        v-if="myResourceList.total.value > 0" @current-change="handleCurrentChange($event, 1)" />
                    </div>
                  </div>
                </el-tab-pane>
                <!-- 我的问答 -->
                <el-tab-pane name="four">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <ChatRound />
                      </el-icon>
                      <span>我的问答</span>
                    </span>
                  </template>
                  <div class="list_container height_light_bgcolor" v-loading="myFaqLoading"
                    element-loading-text="正在玩命加载中...">
                    <Question v-for="item in myFaqList.data.value" :key="item.id" :title="item.title"
                      :desc="item.description" :id="item.id" :tags="item.tags" :num="item.answerNum"
                      :time="item.createTime" :view-number="item.pageViewNum" :author="item.user?.nickName" />
                    <el-empty description="暂无数据~" v-if="!myFaqLoading && myFaqList.total.value <= 0" />
                    <div class="pagination_container">
                      <el-pagination v-model:current-page="myFaqSearchParams.pageNum"
                        v-model:page-size="myFaqSearchParams.pageSize" background
                        layout="total, prev, pager, next, jumper" :total="myFaqList.total.value"
                        v-if="myFaqList.total.value > 0" @current-change="handleCurrentChange($event, 2)" />
                    </div>
                  </div>
                </el-tab-pane>
                <!-- 我的关注 -->
                <el-tab-pane name="five">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <View />
                      </el-icon>
                      <span>我的关注</span>
                    </span>
                  </template>
                  <div class="focu_container height_light_bgcolor">
                    <el-tabs v-model="activeNameFocus" class="demo-tabs" @tab-click="handleClickFocus">
                      <el-tab-pane label="关注的人" name="one">
                        <div class="sub_people_list" v-loading="followLoading" element-loading-text="正在玩命加载中...">
                          <div class="sub_people_item" v-for="item in followData.data.value" :key="item.userId">
                            <div style="display: flex;flex:1;overflow: hidden;align-items: center;">
                              <div class="sub_people_left">
                                <el-avatar :size="50" :src="proxy.$baseImgUrl + item.avatar" class="cursor_class" @click="handleClickToUserBlogDetail(item.userId)" />
                              </div>
                              <div class="sub_people_right">
                                <p class="sub_people_name text_ellipsis cursor_class" @click="handleClickToUserBlogDetail(item.userId)">{{ item.nickName }}</p>
                                <p class="sub_people_desc text_ellipsis hidden-xs-only">{{ item.remark }}</p>
                                <template v-if="item.followType === 0 && userInfoState?.userId !== item.userId">
                                  <el-button round class="hidden-sm-and-up" @click="handleClickFollow(1, item.userId)"
                                    :loading="followBtnLoading">已关注</el-button>
                                </template>
                                <template v-else-if="item.followType === 1 && userInfoState?.userId !== item.userId">
                                  <el-button round class="hidden-sm-and-up" type="primary" :icon="Plus"
                                    @click="handleClickFollow(0, item.userId)"
                                    :loading="followBtnLoading">关注</el-button>
                                </template>
                                <template v-else-if="item.followType === 2 && userInfoState?.userId !== item.userId">
                                  <el-button round class="hidden-sm-and-up" @click="handleClickFollow(1, item.userId)"
                                    :loading="followBtnLoading">互相关注</el-button>
                                </template>
                              </div>
                            </div>
                            <div class="sub_people_end hidden-xs-only">
                              <template v-if="item.followType === 0 && userInfoState?.userId !== item.userId">
                                <el-button round style="margin:10px 0;" @click="handleClickFollow(1, item.userId)"
                                  :loading="followBtnLoading">已关注</el-button>
                              </template>
                              <template v-else-if="item.followType === 1 && userInfoState?.userId !== item.userId">
                                <el-button round style="margin:10px 0;" type="primary" :icon="Plus"
                                  @click="handleClickFollow(0, item.userId)" :loading="followBtnLoading">关注</el-button>
                              </template>
                              <template v-else-if="item.followType === 2 && userInfoState?.userId !== item.userId">
                                <el-button round style="margin:10px 0;" @click="handleClickFollow(1, item.userId)"
                                  :loading="followBtnLoading">互相关注</el-button>
                              </template>
                            </div>
                          </div>
                          <el-empty description="暂无数据~" v-if="!followLoading && followData.data.value <= 0" />
                          <div class="pagination_container">
                            <el-pagination v-model:current-page="followParams.pageNum"
                              v-model:page-size="followParams.pageSize" background
                              layout="total, prev, pager, next, jumper" :total="followData.total.value"
                              v-if="followData.total.value > 0" @current-change="handleCurrentChange($event, 4)" />
                          </div>
                        </div>
                      </el-tab-pane>
                      <el-tab-pane label="粉丝" name="two">
                        <div class="sub_people_list" v-loading="fansLoading" element-loading-text="正在玩命加载中...">
                          <div class="sub_people_item" v-for="item in fansData.data.value" :key="item.userId">
                            <div style="display: flex;flex:1;overflow: hidden;align-items: center;">
                              <div class="sub_people_left">
                                <el-avatar :size="50" :src="proxy.$baseImgUrl + item.avatar" class="cursor_class" @click="handleClickToUserBlogDetail(item.userId)"/>
                              </div>
                              <div class="sub_people_right">
                                <p class="sub_people_name text_ellipsis cursor_class"  @click="handleClickToUserBlogDetail(item.userId)">{{ item.nickName }}</p>
                                <p class="sub_people_desc text_ellipsis hidden-xs-only">{{ item.remark }}</p>
                                <template v-if="item.followType === 0 && userInfoState?.userId !== item.userId">
                                  <el-button round class="hidden-sm-and-up" @click="handleClickFollow(1, item.userId)"
                                    :loading="followBtnLoading">已关注</el-button>
                                </template>
                                <template v-else-if="item.followType === 1 && userInfoState?.userId !== item.userId">
                                  <el-button round class="hidden-sm-and-up" type="primary" :icon="Plus"
                                    @click="handleClickFollow(0, item.userId)"
                                    :loading="followBtnLoading">关注</el-button>
                                </template>
                                <template v-else-if="item.followType === 2 && userInfoState?.userId !== item.userId">
                                  <el-button round class="hidden-sm-and-up" @click="handleClickFollow(1, item.userId)"
                                    :loading="followBtnLoading">互相关注</el-button>
                                </template>
                              </div>
                            </div>
                            <div class="sub_people_end hidden-xs-only">
                              <template v-if="item.followType === 0 && userInfoState?.userId !== item.userId">
                                <el-button round style="margin:10px 0;" @click="handleClickFollow(1, item.userId)"
                                  :loading="followBtnLoading">已关注</el-button>
                              </template>
                              <template v-else-if="item.followType === 1 && userInfoState?.userId !== item.userId">
                                <el-button round style="margin:10px 0;" type="primary" :icon="Plus"
                                  @click="handleClickFollow(0, item.userId)" :loading="followBtnLoading">关注</el-button>
                              </template>
                              <template v-else-if="item.followType === 2 && userInfoState?.userId !== item.userId">
                                <el-button round style="margin:10px 0;" @click="handleClickFollow(1, item.userId)"
                                  :loading="followBtnLoading">互相关注</el-button>
                              </template>
                            </div>
                          </div>
                          <el-empty description="暂无数据~" v-if="!fansLoading && fansData.data.value <= 0" />
                          <div class="pagination_container">
                            <el-pagination v-model:current-page="followParams.pageNum"
                              v-model:page-size="followParams.pageSize" background
                              layout="total, prev, pager, next, jumper" :total="fansData.total.value"
                              v-if="fansData.total.value > 0" @current-change="handleCurrentChange($event, 5)" />
                          </div>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                </el-tab-pane>
                <!-- 浏览历史 -->
                <el-tab-pane name="six">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <Timer />
                      </el-icon>
                      <span>浏览历史</span>
                    </span>
                  </template>
                  <div class="time_line_container height_light_bgcolor">
                    <el-tabs v-model="activeNameHistory" class="demo-tabs" @tab-click="handleClickHistory">
                      <el-tab-pane :label="item.label" :name="item.name" v-for="item in timelineTabPanel"
                        :key="item.id">
                        <el-timeline style="padding-left:0;" v-loading="timeLoading" element-loading-text="正在玩命加载中...">
                          <el-timeline-item :timestamp="item.createTime" placement="top"
                            v-for="item in formatDayDataList" :key="item.id">
                            <el-card shadow="never">
                              <!-- 按道理比对分钟 ，一分钟内可能有多条点击，这里直接对比了秒，没对比分钟，这里应该是循环才对， -->
                              <div class="history_item">
                                <h4 class="history_article_title text_decoration cursor_class"
                                  @click="handleClickToDetail(item.connectId, item.type)">
                                  {{ item.title }}
                                </h4>
                                <div class="history_article_author cursor_class">
                                  <el-avatar :size="30" :src="proxy.$baseImgUrl + item.historyUser?.avatar" />
                                  <span style="margin-left:8px" class="text_ellipsis">{{ item.historyUser?.nickName
                                  }}</span>
                                </div>
                              </div>
                            </el-card>
                          </el-timeline-item>
                        </el-timeline>
                        <div class="btn_loading">
                          <el-button type="primary" v-if="!timeLoading && !isMore" :loading="loadmoreBtn"
                            @click="handleClickLoadMore">加载更多</el-button>
                        </div>
                        <div style="color:#b1b1b1;font-size:14px;text-align: center;" v-if="isMore">
                          我也是有底线的😓！
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                </el-tab-pane>
                <!-- 修改密码 -->
                <el-tab-pane name="seven">
                  <template #label>
                    <span class="left_label">
                      <el-icon>
                        <Lock />
                      </el-icon>
                      <span>修改密码</span>
                    </span>
                  </template>
                  <div class="height_light_bgcolor change_psw_container">
                    <el-form ref="changePswRuleFormRef" :model="changePswRuleForm" :rules="changePswRules"
                      label-width="120px" :size="formSize" status-icon style="max-width:800px">
                      <el-form-item label="旧密码" prop="oldPassword">
                        <el-input v-model="changePswRuleForm.oldPassword" type="password" />
                      </el-form-item>
                      <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model="changePswRuleForm.newPassword" type="password" />
                      </el-form-item>
                      <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input v-model="changePswRuleForm.confirmPassword" type="password" />
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="submitFormChangePsw(changePswRuleFormRef)" style="width:300px"
                          :loading="changePswConfirmLoading">确定</el-button>
                        <el-button @click="resetForm(changePswRuleFormRef)">重置</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-col>
        </el-row>
      </template>
    </layout>
    <Footer />
    <el-dialog v-model="dialogVisible" title="编辑个人信息" width="50%">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
        :size="formSize" status-icon>
        <el-form-item label="头像" prop="avatar">
          <upload-image :limit="1" @input="handleUploadImage" v-model="ruleForm.avatar"></upload-image>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="ruleForm.nickName" />
        </el-form-item>
        <el-form-item label="个人简介" prop="remark">
          <el-input :rows="2" type="textarea" v-model="ruleForm.remark" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="0" size="large">男</el-radio>
            <el-radio label="1" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机" prop="phonenumber">
          <el-input v-model="ruleForm.phonenumber" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="兴趣" prop="">
          <el-select v-model="ruleForm.interests" placeholder="请选择兴趣,最多可选择5个" multiple :reserve-keyword="false"
            style="width:100%;" :multiple-limit="5">
            <el-option v-for="item in groupOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" style="width:300px"
            :loading="confirmLoading">确定</el-button>
          <el-button @click="() => { dialogVisible = false }">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import Menu from '@/components/Menu/index.vue'
import Layout from '@/components/Layout/index.vue'
import Footer from '@/components/Footer/index.vue'
import { computed, getCurrentInstance, onMounted, reactive, ref, toRefs, watch } from 'vue'
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  Search,
  Plus,
  Edit,
  User,
  View,
  Timer,
  Files,
  Lock,
  ChatRound
} from '@element-plus/icons-vue'
import { TabsPaneContext, FormInstance, FormRules, ElMessage } from 'element-plus'
import { getUserInfo, editUserInfo, editUserPsw, getHistoryList, getUserFollows, getUserFans, followUser } from '@/api/user'
import { getGroup } from "@/api/dictionary";
import uploadImage from '@/components/Upload/index.vue'
import { useStore } from "vuex";
import dayjs from 'dayjs'
import { number } from '@intlify/core-base'
import router from '@/router'
import { RouteLocation } from 'vue-router'
import Article from '@/components/Article/index.vue'
import Question from '@/components/Question/index.vue'
import File from '@/components/File/index.vue'
import { getBlogList } from "@/api/index";
import { getFaqList } from '@/api/faq'
import { getResourceList } from "@/api/download";
import { totalmem } from 'os'
const store = useStore();
const { proxy } = getCurrentInstance()
const userInfoData = reactive<any>({ data: {} })
const tabPosition = ref('left')
const activeName = ref<any>('first')
const activeNameFocus = ref<any>('one')
const activeNameHistory = ref<any>('today')
const dialogVisible = ref<boolean>(false)
const formSize = ref('large')
const ruleFormRef = ref<FormInstance>()
const changePswRuleFormRef = ref<FormInstance>()
const groupOptions = ref<any>([])
const confirmLoading = ref<boolean>(false)
const changePswConfirmLoading = ref<boolean>(false)
const ruleForm = reactive({
  avatar: '',
  nickName: '',
  remark: '',
  sex: '0',
  phonenumber: '',
  email: '',
  interests: '',
  userId: '',
  userName: ''
})
const changePswRuleForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const changePswRules = reactive<FormRules>({
  oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
  newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
  confirmPassword: [{ required: true, message: '确认密码不能为空', trigger: 'blur' }]
})
const userInfoState = computed(() => store.state.userInfo);
const historySearchParams = reactive<any>({
  pageNum: 1,
  pageSize: 20
})
// const validatorPhone = (rule: any, value: any, callback: any) => {
//   if (ruleForm.phonenumber !== '') {
//     if (!ruleFormRef.value) return
//     ruleFormRef.value.validateField('checkPass', () => null)
//   }
//   callback()
// }
const rules = reactive<FormRules>({
  nickName: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 2, max: 8, message: '昵称长度必须在2到8个字符之间', trigger: 'blur' },
  ],
  // phonenumber: [
  //   {
  //     validator: validatorPhone,
  //     trigger: 'blur'
  //   }
  // ],
  // email: [
  //   {
  //     validator: validatorEmail,
  //     trigger: 'blur'
  //   }
  // ],
})
const historyData = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const formatDayDataList = ref<any>([])
const timeLoading = ref<boolean>(false)
const loadmoreBtn = ref<boolean>(false)
const isMore = ref<boolean>(false)
const timelineTabPanel = ref<any>([{
  id: 1,
  label: '今日',
  name: 'today'
}, {
  id: 2,
  label: '昨日',
  name: 'yesterday'
}, {
  id: 3,
  label: '近一周',
  name: 'weekago'
},])
const myArticleList = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const myArticleSearchParams = reactive<any>({
  pageNum: 1,
  pageSize: 10
})
const myArticleLoading = ref<boolean>(false)
const myFaqList = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const myFaqSearchParams = reactive<any>({
  pageNum: 1,
  pageSize: 10
})
const myFaqLoading = ref<boolean>(false)
const myResourceList = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const myResourceSearchParams = reactive<any>({
  pageNum: 1,
  pageSize: 10
})
const myResourceLoading = ref<boolean>(false)
const followData = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const followParams = reactive<any>({
  pageNum: 1,
  pageSize: 10
})
const followLoading = ref<boolean>(false)
const fansLoading = ref<boolean>(false)
const fansParams = reactive<any>({
  pageNum: 1,
  pageSize: 10
})
const fansData = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const followBtnLoading = ref<boolean>(false)
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('submit!')
      try {
        confirmLoading.value = true
        const interests = ruleForm.interests ? ruleForm.interests.toString() : null
        const res: any = await editUserInfo({ ...ruleForm, interests, })
        if (res) {
          ElMessage({
            message: "修改成功",
            type: 'success',
            duration: 2 * 1000
          })
          getUserInfoData()
          if (!ruleForm.avatar) {
            ruleForm.avatar = userInfoData.data.avatar
          }
          setTimeout(() => {
            dialogVisible.value = false
            resetForm(formEl)
          }, 500);
        }
      } finally {
        confirmLoading.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const getUserFollowsData = async () => {
  try {
    followLoading.value = true
    const { rows, total }: any = await getUserFollows({
      ...followParams,
      userId: userInfoData.data.userId
    })
    followData.data.value = rows

    followData.total.value = total
  } finally {
    followLoading.value = false
  }
}
const getUserFansData = async () => {
  try {
    fansLoading.value = true
    const { rows, total }: any = await getUserFans({
      ...fansParams,
      userId: userInfoData.data.userId
    })
    fansData.data.value = rows
    fansData.total.value = total
  } finally {
    fansLoading.value = false
  }
}
const handleClick = async (tab: TabsPaneContext, event: Event) => {
  const { name } = tab.props
  activeName.value = name
  if (activeName.value === 'first') {

  } else if (activeName.value === 'second') {
    myArticleSearchParams.pageNum = 1
    getBlogListData()
  } else if (activeName.value === 'third') {
    myResourceSearchParams.pageNum = 1
    getResourceListData()
  } else if (activeName.value === 'four') {
    myFaqSearchParams.pageNum = 1
    getFaqListData()
  } else if (activeName.value === 'five') {
    activeNameFocus.value = "one"
    followParams.pageNum = 1
    getUserFollowsData()
  } else if (activeName.value === 'six') {
    activeNameHistory.value = 'today'
    resetSerachParams()
    await getHistoryListData()
    let todayStr = dayjs(new Date()).format('YYYY-MM-DD')
    formatDayData(new Date(todayStr).getTime(), true)
  } else if (activeName.value === 'seven') {

  }

}
const handleClickFocus = (tab: TabsPaneContext, event: Event) => {
  const { name } = tab.props
  activeNameFocus.value = name
  if (activeNameFocus.value === "one") {
    followParams.pageNum = 1
    getUserFollowsData()
  } else {
    fansParams.pageNum = 1
    getUserFansData()
  }
}
const handleClickHistory = async (tab: TabsPaneContext, event: Event) => {
  const { name } = tab.props
  activeNameHistory.value = name
  resetSerachParams()
  await getHistoryListData()
  let daystr: string = ''
  if (activeNameHistory.value === 'today') {
    daystr = dayjs(new Date()).format('YYYY-MM-DD')
    formatDayData(new Date(daystr).getTime(), true)
  } else if (activeNameHistory.value === 'yesterday') {
    daystr = dayjs(new Date().getTime() - 3600 * 1000 * 24).format('YYYY-MM-DD')
    formatDayData(new Date(daystr).getTime(), true)
  } else if (activeNameHistory.value === 'weekago') {
    formatDayData(null, false)
  }
}
const resetSerachParams = () => {
  historySearchParams.pageNum = 1
  formatDayDataList.value = []
  isMore.value = false
}
const formatDayData = (day: number | null, flag: boolean) => {
  historyData.data.value.forEach((item: { createTime: string }) => {
    // console.log(new Date(item.createTime.split(' ')[0]).getTime());
    if (new Date(item.createTime.split(' ')[0]).getTime() == day) {
      formatDayDataList.value.push(item)
    } else if (!flag) {
      let todyStr = new Date(dayjs(new Date()).format('YYYY-MM-DD')).getTime()
      let yesterdayStr = new Date(dayjs(new Date().getTime() - 3600 * 1000 * 24).format('YYYY-MM-DD')).getTime()
      if (new Date(item.createTime.split(' ')[0]).getTime() != todyStr && new Date(item.createTime.split(' ')[0]).getTime() != yesterdayStr) {
        formatDayDataList.value.push(item)
      }
    }
  });
  if (historySearchParams.pageNum * historySearchParams.pageSize >= historyData.total.value) {
    isMore.value = true
  }
  timeLoading.value = false
}
const handleClickLoadMore = async () => {
  try {
    loadmoreBtn.value = true
    historySearchParams.pageNum++
    await getHistoryListData()
    let daystr: string = ''
    if (activeNameHistory.value === 'today') {
      daystr = dayjs(new Date()).format('YYYY-MM-DD')
      formatDayData(new Date(daystr).getTime(), true)
    } else if (activeNameHistory.value === 'yesterday') {
      daystr = dayjs(new Date().getTime() - 3600 * 1000 * 24).format('YYYY-MM-DD')
      formatDayData(new Date(daystr).getTime(), true)
    } else if (activeNameHistory.value === 'weekago') {
      // daystr = dayjs(new Date().getTime() - 3600 * 1000 * 7).format('YYYY-MM-DD')
      formatDayData(null, false)
    }

  } finally {
    loadmoreBtn.value = false
  }

}
const submitFormChangePsw = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('submit!')
      if (changePswRuleForm.confirmPassword !== changePswRuleForm.newPassword) {
        return ElMessage({
          message: "两次密码输入不一致",
          type: 'error',
          duration: 2 * 1000
        })
      }
      try {
        changePswConfirmLoading.value = true
        const res: any = await editUserPsw(changePswRuleForm)
        if (res) {
          ElMessage({
            message: "密码修改成功，请重新登录",
            type: 'success',
            duration: 2 * 1000
          })
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          store.commit("updataUser", {});
          location.reload()
        }
      } finally {
        changePswConfirmLoading.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
/**
 * 获取用户浏览记录
 */
const getHistoryListData = async () => {
  try {
    timeLoading.value = true
    const { rows, total }: any = await getHistoryList(historySearchParams)
    historyData.data.value = rows
    historyData.total.value = total
    if (historySearchParams.pageNum * historySearchParams.pageSize >= historyData.total.value) {
      isMore.value = true
    }
  } finally {
    timeLoading.value = false
  }
}
/**
 * 获取用户信息
 */
const getUserInfoData = async () => {
  if (localStorage.getItem('token')) {
    const { data }: any = await getUserInfo()
    userInfoData.data = data
    ruleForm.userId = userInfoData.data.userId
    ruleForm.userName = userInfoData.data.userName
    ruleForm.avatar = userInfoData.data.avatar
    ruleForm.nickName = userInfoData.data.nickName
    ruleForm.remark = userInfoData.data.remark
    ruleForm.sex = userInfoData.data.sex
    ruleForm.phonenumber = userInfoData.data.phonenumber
    ruleForm.email = userInfoData.data.email
    let tagarr = userInfoData.data.interests.split(',').map((item: string) => (Number(item)))
    // console.log(tagarr);
    ruleForm.interests = tagarr
    // ruleForm.interests = Number(userInfoData.data.interests).split(',')
    store.commit("updataUser", data);
    localStorage.setItem('userInfo', JSON.stringify(data))
  }
}
const handleClickEditUserInfo = () => {
  dialogVisible.value = true
  getUserInfoData()
}
// 获取全部方向
const getGroupData = async () => {
  const { data }: any = await getGroup()
  groupOptions.value = data.map((item: { id: number; name: string; }) => ({ value: item.id, label: item.name }))
}
const handleUploadImage = (file: string) => {
  ruleForm.avatar = file
}
const handleClickToDetail = (id: string, type: number) => {
  let url: RouteLocation & { href: string; }
  if (type === 0) {
    url = router.resolve({
      name: 'article-detail',
      params: {
        id
      }
    })
    window.open(url.href, '_blank')
  } else if (type === 1) {
    url = router.resolve({
      name: 'faq-detail',
      params: {
        id
      }
    })
    window.open(url.href, '_blank')
  } else if (type === 2) {
    url = router.resolve({
      name: 'download-detail',
      params: {
        id
      }
    })
    window.open(url.href, '_blank')
  }
}
// 获取我的博客列表
const getBlogListData = async () => {
  try {
    myArticleLoading.value = true
    const { rows, total }: any = await getBlogList({
      authorId: ruleForm.userId,
      ...myArticleSearchParams
    })
    myArticleList.data.value = rows
    myArticleList.total.value = total
  } finally {
    myArticleLoading.value = false
  }
}
// 监听点赞，更新数据
const handleClickArticleLiked = (e: any, name: string) => {
  getBlogListData()
}
const handleCurrentChange = (e: any, num: number) => {
  if (num === 1) {
    // 我的博客
    myArticleSearchParams.pageNum = e
    getBlogListData()
  } else if (num === 2) {
    myFaqSearchParams.pageNum = e
    getFaqListData()
  } else if (num === 3) {
    myResourceSearchParams.pageNum = e
    getResourceListData()
  } else if (num === 4) {
    followParams.pageNum = e
    getUserFollowsData()
  } else if (num === 5) {
    fansParams.pageNum = e
    getUserFansData()
  }
}
const getFaqListData = async () => {
  try {
    myFaqLoading.value = true
    const { rows, total }: any = await getFaqList({
      ...myFaqSearchParams,
      userId: ruleForm.userId
    })
    myFaqList.data.value = rows
    myFaqList.total.value = total
  } finally {
    myFaqLoading.value = false
  }
}
const getResourceListData = async () => {
  try {
    myResourceLoading.value = true
    const { rows, total }: any = await getResourceList({
      ...myResourceSearchParams,
      userId: ruleForm.userId
    })
    myResourceList.data.value = rows
    myResourceList.total.value = total
  } finally {
    myResourceLoading.value = false
  }
}
// 关注
const handleClickFollow = async (status: number, followedUserId: number) => {
  try {
    followBtnLoading.value = true
    const res: any = await followUser({
      followedUserId,
      status
    })
    if (res) {
      if (status === 1) {
        ElMessage({
          message: '取关成功',
          type: 'success',
          duration: 2 * 1000
        })
      } else {
        ElMessage({
          message: '关注成功',
          type: 'success',
          duration: 2 * 1000
        })
      }
      getUserFansData()
      getUserFollowsData()
    }
  } finally {
    followBtnLoading.value = false
  }
}
const handleClickToUserBlogDetail = (id: number) => {
  const url = router.resolve({
    name: 'user-blog',
    params: {
      id
    }
  })
  window.open(url.href, '_blank')
}
onMounted(() => {
  getUserInfoData()
  getGroupData()
})

</script>

<style scoped lang="scss">
// @import '@/assets/style/reset.scss';
@import './index.scss';

:deep(.el-tabs__nav-wrap) {
  background: #fff;
}

:deep(.el-tabs__item) {
  height: auto;
  padding: 10px 60px;
}

:deep(.el-tabs__header) {
  height: 100vh !important;
}

:deep(.el-tabs__nav-wrap:after) {
  background: #fff;
}

:deep(.demo-tabs .el-tabs__item) {
  padding: 0 20px;
}

:deep(.demo-tabs .el-tabs__nav-wrap:after) {
  background: var(--el-border-color-light) !important;
}

:deep(.demo-tabs .el-tabs__header) {
  height: inherit !important;
}
</style>
